package de.openlaboratory.labhub.core.framework;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletRequest;

public class Helper
{
	private static final String LABHUB_TOKEN = "labhub";

	public static boolean isPortAvailable(int port)
	{
		try
		{
			ServerSocket srv = new ServerSocket(port);
			srv.close();
			srv = null;
			return true;
		}
		catch (IOException e)
		{
			return false;
		}
		catch (Exception e)
		{
			return true;
		}
	}

	public static <T> String join(final Iterable<T> objs, final String delimiter)
	{
		Iterator<T> iter = objs.iterator();
		if (!iter.hasNext())
			return "";
		StringBuffer buffer = new StringBuffer(String.valueOf(iter.next()));
		while (iter.hasNext())
			buffer.append(delimiter).append(String.valueOf(iter.next()));
		return buffer.toString();
	}

	public static ArrayList<String> getElementsByTagName(String c, String tagName)
	{
		ArrayList<String> tags = new ArrayList<String>();
		String pattern = "<\\w*" + tagName + "\\w*(.+?)\\w*/>";
		
		// the pattern we want to search for
		Pattern p = Pattern.compile(pattern, Pattern.MULTILINE);
		Matcher m = p.matcher(c);

		// print all the matches that we find
		while (m.find())
		{
			tags.add(m.group(1));
		}

		return tags;
	}
	
	public static ArrayList<String> getValuesByAttributeName(ArrayList<String> list, String attributeName)
	{
		ArrayList<String> values = new ArrayList<String>();
		String pattern = attributeName + "\\w*=\\w*\"(.+?)\"";
		
		// the pattern we want to search for
		Pattern p = Pattern.compile(pattern, Pattern.MULTILINE);
		
		for (String attr : list)
		{
			Matcher m = p.matcher(attr);
			// print all the matches that we find
			while (m.find())
			{
				values.add(m.group(1));
			}
		}
		
		return values;
	}
	
	public static ArrayList<String> getTokens(String c)
	{
		return getValuesByAttributeName(getElementsByTagName(c, LABHUB_TOKEN), "name");
	}
}